<?php

class SiteController extends Controller {

    public $msg = '请求异常';

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'login', 'account', 'validate'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform any actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete,update', // we only allow deletion via POST request
        );
    }

    public function actionIndex() {
        $schools = School::model()->loadSchools();
        $this->render('index', array('schools' => $schools));
    }

    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionContact() {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $name = '=?UTF-8?B?' . base64_encode($model->name) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode($model->subject) . '?=';
                $headers = "From: $name <{$model->email}>\r\n" .
                        "Reply-To: {$model->email}\r\n" .
                        "MIME-Version: 1.0\r\n" .
                        "Content-type: text/plain; charset=UTF-8";

                mail(Yii::app()->params['adminEmail'], $subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    public function actionLogin() {
        $model = new LoginForm();
        if (isset($_POST['username'])) {
            $model->username = $_POST['username'];
            $model->password = $_POST['password'];
            $model->rememberMe = $_POST['remember'] === "true" ? true : false;
            // validate user input and redirect to the previous page if valid
            $data = array();
            if ($model->validate() && $model->login()) {
                $data['r'] = 1;
                $data['msg'] = 'http://link.com/link/index/';
            } else {
                $data['r'] = 0;
                $data['msg'] = '用户名或密码错误';
            }
            echo CJSON::encode($data);
            Yii::app()->end();
        }
        // display the login form
        if (isset($_GET['id']) && !empty($_GET['id'])) {
            Yii::app()->session->add('school_code', $_GET['id']);
            $schools = School::model()->loadSchools();
            foreach ($schools as $school) {
                if ($school->code === $_GET['id']) {
                    $this->render('login', array('school' => $school));
                    Yii::app()->end();
                    break;
                }
            }
        }
        $this->redirect('index');
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    /**
     * 后台需要再次验证一遍
     */
    public function actionAccount() {
        $user = new User();
        if (isset($_POST['User'])) {
            $user->attributes = $_POST['User'];
            if (!$user->isExistUsername($user->username) && !$user->isExistEmail($user->email) &&
                    $user->validate()) {
                $user->save();
                $this->redirect('/link/index');
            }
            $this->msg = '注册失败,请重新再试一次';
        }

        $this->render('account');
    }

    /**
     * //判断用户名是否存在
      //昵称是否存在
      //email是否存在
     */
    public function actionValidate() {
        $data = array();
        $data['r'] = 1;
        $data['msg'] = '';
        if (isset($_POST['col']) && isset($_POST['colVal'])) {
            if ($_POST['col'] === 'username') {
                $username = $_POST['colVal'];
                if (User::model()->isExistUsername($username)) {
                    $data['r'] = 0;
                    $data['msg'] = '用户名已经存在';
                }
            } else if ($_POST['col'] === 'email') {
                $email = $_POST['colVal'];
                if (User::model()->isExistEmail($email)) {
                    $data['r'] = 0;
                    $data['msg'] = '邮箱已经使用';
                }
            }
        }
        $json = CJSON::encode($data);
        echo $json;
        Yii::app()->end();
    }

}